<?php
/**
 * 上传shopify产品
 * User: bgl
 * Date: 2022/9/7
 * Time: 16:44
 */

namespace App\Admin\Controllers\Products;


use App\Importer\Basics\BImporter;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\SysCountry;
use App\Models\Product\ProductShopifySku;
use App\Models\Product\ProductShopifySkuCCS;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ShopifySkuUploadController extends AdminController{

    protected $title = 'Shopify产品上传';

    protected function grid()
    {
        $type = request('type');
        return view("products.shopify-sku.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importShopifySku(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(), $file);
            $data = $data[0];

            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $classify = [];
            $seller = [];
            $userId = Admin::user()->id;

            foreach($data as $row){
                $count++;
                $sku       = $row[0] ? trim($row[0]) : '';
                $sellerSku = $row[1] ? trim($row[1]) : '';
                $account   = $row[2] ? trim($row[2]) : '';
                $_country  = $row[3] ? trim($row[3]) : '';
                $upcType   = $row[4] ? trim($row[4]) : '无';
                $upc       = $row[5] ? trim($row[5]) : '无';
                $_status   = $row[6] ? trim($row[6]) : '停用';

                if(!$sku || !$sellerSku || !$account || !$_country){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                $country = strtoupper($_country);
                $key = $sellerSku.'_'.$country;
                if(!in_array($key, $arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }

                if(!in_array($upcType, ProductShopifySku::$_barcodeType)){
                    $errors[$count] = '['.$upcType.'],不存在，请选择条码类型: '.implode('、', ProductShopifySku::$_barcodeType);
                    continue;
                }
                $upcTypeId = array_search($upcType, ProductShopifySku::$_barcodeType);
                if($upcTypeId == 3){
                    $upc = '无';
                }
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = '['.$_country.'],系统不存在该国家';
                    continue;
                }

                //验证平台账号
                $accountId = SysPlatAccount::getIdByAccount($account);
                if(!$accountId){
                    $errors[$count] = '['.$account.'],系统不存在该平台账号';
                    continue;
                }

                $pSkuId = ProductSku::getValueByCode($sku, 'id');
                if(!$pSkuId){
                    $errors[$count] = '['.$sku.'],系统不存在该SKU';
                    continue;
                }

                $status = array_search($_status, ProductShopifySku::$_status);
                if(!$status){
                    $errors[$count] = '['.$_status.'],不存在该状态，请选择'.implode('、',ProductShopifySku::$_status);
                    continue;
                }

                $reCount = ProductShopifySku::query()
                    ->where('seller_sku', $sellerSku)
                    ->where('country_id', $countryId)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = '['.$key.'],系统已存在该平台商品，需要更新请前往更新';
                    continue;
                }

                //销售
                if(!array_key_exists($pSkuId,$classify)) {
                    $classify[$pSkuId] = ProductSku::getValueById($pSkuId, 'classify_id');
                }
                $classifyId = $classify[$pSkuId];
                $sellerKey = $classifyId.'_'.$countryId;
                if(!array_key_exists($sellerKey,$seller)){
                    $ccs = ProductShopifySkuCCS::returnSellerId($countryId, $classifyId, $userId);
                    $seller[$sellerKey] = $ccs->seller_id;
                }
                $sellerId = $seller[$sellerKey];

                DB::beginTransaction();
                $pas = ProductShopifySku::query()->create([
                    'seller_sku' => $sellerSku,
                    'country_id' => $countryId,
                    'psku_id' => $pSkuId,
                    'barcode_type' => $upcTypeId,
                    'barcode' => $upc,
                    'account_id' => $accountId,
                    'seller_id' => $sellerId,
                    'cuser_id' => $userId,
                    'status' => $status,
                ]);
                if($pas){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }

            if(empty($errors)){
                return ['flag' => true, 'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false, 'data' => '系统异常！'];
        }
    }

    private function _importShopifySkuUp(UploadedFile $file){
        try{
            $data = Excel::toArray(new bImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $classify = [];
            $seller = [];
            $userId = Admin::user()->id;

            foreach($data as $row){
                $count++;
                $sellerSku  = $row[0] ? trim($row[0]) : '';
                $_country   = $row[1] ? trim($row[1]) : '';
                $upcType    = $row[2] ? trim($row[2]) : '';
                $upc        = $row[3] ? trim($row[3]) : '';
                $status     = $row[4] ? trim($row[4]) : '';

                if(!$sellerSku || !$_country){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                $country = strtoupper($_country);
                $key = $sellerSku.'_'.$country;
                if(!in_array($key, $arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = '['.$_country.'],系统不存在该国家';
                    continue;
                }

                DB::beginTransaction();
                $pas = ProductShopifySku::query()
                    ->where('seller_sku', $sellerSku)
                    ->where('country_id', $countryId)
                    ->first();
                if(!$pas){
                    $errors[$count] = '['.$key.'],系统已存在该平台商品，需要新增请前往新增';
                    DB::rollBack();
                    continue;
                }

                $upcTypeId = $pas->barcode_type;
                if($upcType){
                    if(!in_array($upcType, ProductShopifySku::$_barcodeType)){
                        $errors[$count] = '['.$upcType.'],不存在该条码，请选择'.implode('、', ProductShopifySku::$_barcodeType);
                        DB::rollBack();
                        continue;
                    }
                    $upcTypeId = array_search($upcType, ProductShopifySku::$_barcodeType);
                    $pas->barcode_type = $upcTypeId;
                }

                if($upc){
                    $pas->barcode = $upcTypeId == 3 ? '无' : $upc;
                }

                if(!$status){
                    if(!in_array($status,ProductShopifySku::$_status)){
                        $errors[$count] = $status.'不存在，请选择'.implode('、',ProductShopifySku::$_status);
                        continue;
                    }
                    $pas->status = array_search($status,ProductShopifySku::$_status);
                }

                //销售
                if($pas->country_id != $countryId){
                    if(!array_key_exists($pas->psku_id,$classify)) {
                        $classify[$pas->psku_id] = ProductSku::getValueById($pas->psku_id, 'classify_id');
                    }
                    $classifyId = $classify[$pas->psku_id];
                    $sellerKey = $classifyId.'_'.$countryId;
                    if(!array_key_exists($sellerKey,$seller)){
                        $ccs = ProductShopifySkuCCS::returnSellerId($countryId, $classifyId,$userId);
                        $seller[$sellerKey] = $ccs->seller_id;
                    }
                    $sellerId = $seller[$sellerKey];
                    $pas->seller_id = $sellerId;
                }

                if($pas->save()){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }

            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
